import Vue from 'vue';
import NoticeBox from './notice-box';

const noticeBoxProxy = (() => {
  const el = document.createElement('div');
  document.body.appendChild(el);

  const noticeBox = new Vue({
    el,
    template: '<notice-box></notice-box>',
    components: {
      NoticeBox,
    },
  }).$children[0];

  return {
    add(notice) {
      noticeBox.add(notice);
    },
    remove(key) {
      noticeBox.remove(key);
    },
  };
})();

const noticeHub = {
  open(args) {
    const duration = args.duration ? args.duration : 4.5;
    if (args.type === 'text') {
      const noticeClassName = 't-notice--text';
      noticeBoxProxy.add({
        content: `
        <p class="${noticeClassName}__message">${args.message}</p>
        <p class="${noticeClassName}__description">${args.description}</p>`,
        duration,
        closable: true,
        onClose: args.onClose,
        type: 'text',
      });
    } else if (args.type === 'icon') { // <i class="${noticeClassName}__icon ${iconClassName}"></i>
      const noticeClassName = 't-notice--icon';
      const iconClassName = 'iconfont icon-xinxi';
      noticeBoxProxy.add({
        content: `
        <img class="${noticeClassName}__icon ${iconClassName}" src="https://www.todaytomato.com:8055/logo.png" style="width: 1.3rem; margin-bottom: -0.2rem;"></img>
        <p class="${noticeClassName}__message">${args.message}</p>
        <p class="${noticeClassName}__description">${args.description}</p>`,
        duration,
        closable: true,
        onClose: args.onClose,
        type: 'icon',
      });
    } else {
      noticeBoxProxy.add({
        content: `<p class="t-notice--tomato__message">${args.message}</p>`,
        duration,
        closable: true,
        onClose: args.onClose,
        type: 'tomato',
      });
    }
  },
  close(key) {
    if (noticeBoxProxy) {
      noticeBoxProxy.remove(key);
    }
  },
};

['text', 'success', 'info', 'warn', 'error', 'tomato'].forEach((type) => {
  noticeHub[type] = (args) => {
    if (type === 'tomato') {
      return noticeHub.open(Object.assign({}, args, { type: 'tomato' }));
    } else if (type === 'text') {
      return noticeHub.open(Object.assign({}, args, { type: 'text' }));
    }
    return noticeHub.open(Object.assign({}, args, { type: 'icon' }, { icon: type }));
  };
});

export default noticeHub;
